package com.teamtgv.shareshark.task;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.teamtgv.shareshark.AppData;
import com.teamtgv.shareshark.JSONParser;
import com.teamtgv.shareshark.result.Result;

public class GetRecentRecommendationsTask extends AsyncTask<Void, String, ArrayList<Result>>{

		public static final String LOG_TAG = AskRecommendationsTask.class.getSimpleName();
		private Context context;
		private ProgressDialog pDialog;
		
		public GetRecentRecommendationsTask(Context context) {
			this.context = context;
		}
		
	    /**
	     * Before starting background thread Show Progress Dialog
	     * */
	    @Override
	    protected void onPreExecute() {
	        super.onPreExecute();
	        pDialog = new ProgressDialog(context);
	        pDialog.setMessage("Retrieving results...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(true);
	        pDialog.show();
	    }
		
		@Override
		protected ArrayList<Result> doInBackground(Void... args) {
		
			
	        Log.v(LOG_TAG, "Retrieving recent db results");
	        List<NameValuePair> params = new ArrayList<NameValuePair>();
	        
	        JSONParser jsonParser = new JSONParser();
	        int counter = 0; // counter
	        
	        JSONObject json = null;
	        while (json == null && counter < 5) {
	        	json = jsonParser.makeHttpRequest(AppData.FULL_HOST + "get_recent_recommendations.php", "GET", params);
	        	if (json == null) {
	        		Log.v(LOG_TAG, "JSON object from HTTP request is null at attempt " + counter);
	        	}
	        	counter++;
	        }
	        if (json == null)
	        	return null;
	        
	        // check log cat fro response
	        Log.d("Create Response", json.toString());

	        // check for success tag
	        try {
	            int success = json.getInt("success");

	            if (success == 1) {
	                // successfully created product
	            	Log.v(LOG_TAG, "Request successful");
	            	
	            	ArrayList<Result> resultList = new ArrayList<Result>();

	            	 // products found
	                // Getting Array of Products
	                JSONArray recommendations = json.getJSONArray("recommendations");

	                // looping through All Products
	                for (int i = 0; i < recommendations.length(); i++) {
	                    JSONObject recommendation = recommendations.getJSONObject(i);

	                    // Storing each json item in variable
	                    int id = recommendation.getInt("id");
	                    BigInteger recommenderFacebookId = new BigInteger(recommendation.getString("by"));
	                    String whatResult = recommendation.getString("what");
	                    String whereResult = recommendation.getString("where");
	                    BigInteger targetFacebookId = new BigInteger(recommendation.getString("to"));
	                    String dateResult = recommendation.getString("date");
	                    int ratingPlusResult = recommendation.getInt("rating_plus");
	                    int ratingMinResult = recommendation.getInt("rating_min");
	                    String imageUrlResult = recommendation.getString("imageUrl");

	                    Result result = new Result(id, recommenderFacebookId, targetFacebookId, whatResult, whereResult, dateResult, ratingPlusResult, ratingMinResult, imageUrlResult);
	                    resultList.add(result);

	                }
	                // closing this screen
	                return resultList;
	            } else {
	                // failed to create product
	            }
	        } catch (JSONException e) {
	            e.printStackTrace();
	        }

	        return null;
		}
		
	    /**
	     * After completing background task Dismiss the progress dialog
	     * **/
	    protected void onPostExecute(ArrayList<Result> result) {
	        // dismiss the dialog once done
	        pDialog.dismiss();
	    }
	
}
